# Create your views here.

from django.views import View

from model.models import User, Point
from server.utils import Response, Request, LoginRequiredSuperAdmin, Verify, Code


class PointView(LoginRequiredSuperAdmin, View):
    """ Query point information """

    def get(self, request):
        """ Get point information """
        uid = request.GET.get('uid')
        phone = request.GET.get('phone')
        type = request.GET.get('type')
        status = request.GET.get('status')

        points = Point.objects.all()
        if uid:
            points = points.filter(uploader__uid__contains=uid)
        if phone:
            points = points.filter(uploader__phone__contains=phone)
        if type and int(type) in Point.Type:
            points = points.filter(type=type)
        if status and int(status) in Point.Status:
            points = points.filter(status=status)

        points = [{**point.info()} for point in points]
        return Response.Json(points=points)

    @Request.getJson
    def post(self, request):
        """ Modifying point information """
        pid = request.JSON.get('pid')
        name = request.JSON.get('name')
        detail = request.JSON.get('detail')
        longitude = request.JSON.get('longitude')
        latitude = request.JSON.get('latitude')
        direction = request.JSON.get('direction')
        code = Verify.pointPid(pid)
        if code != Code.OK:
            return Response.Json(code=code)

        point = Point.objects.get(pid=pid)
        if name and Verify.pointName(name) == Code.OK:
            point.name = name
        if detail and Verify.pointDetail(detail) == Code.OK:
            point.detail = detail
        if longitude and Verify.longitude(longitude) == Code.OK:
            point.longitude = longitude
        if latitude and Verify.latitude(latitude) == Code.OK:
            point.latitude = latitude
        if direction is not None and Verify.direction(direction) == Code.OK:
            point.direction = direction

        point.save()
        return Response.Json()

    @Request.getJson
    def delete(self, request):
        """ Delete point """
        pid = request.JSON.get('pid')

        code = Verify.pointPid(pid)
        if code != Code.OK:
            return Response.Json(code=code)

        point = Point.objects.get(pid=pid)
        point.delete()
        return Response.Json()
